const router=require('koa-router')();
const events=require('events');
const {post:postProxy}=require('../proxy/index');
const {User}=require('../models/index');
const checkPage=require('../middlewares/checkPage');
const Page=require('../lib/page');

//搜索
router.get('/',checkPage(),async ctx=>{
    let {keyword}=ctx.query,ee=new events();
    keyword=keyword.trim();
    ee.on('invalid',msg=>{
        ctx.flash={notify:msg};
        ctx.redirect('/notify');
    });

    if(!keyword.length)return ee.emit('invalid','请输入关键字');

    let invalid=[
        //'c','f','n','r','t','v','0','x','u',
        //'s','S','w','W','d','D','b','B',
        '$','^',
        '(',')','[',']','{','}',
        '*','+','-','.','?',':','=','!',
        '\\','|'
    ];

    let clean=keyword.replace(/./g,function(s){
        if(invalid.includes(s))return '\\'+s;
        return s;
    });
    let reg=new RegExp(clean,'ig');

    let [{total,page,posts},noRplies,top10]=await Promise.all([
        postProxy.getList({title:reg},null,{page:ctx.query.p}),
        postProxy.getList({comments:{$size:0}},null,{limit:5}),
        User.find(null,{name:true,score:true},{skip:0,limit:5,sort:{score:-1}})
    ]);

    await ctx.render('search',{
        title:'Search:'+keyword,
        loginUser:ctx.session.loginUser,
        posts,
        noReplies:noRplies.posts,
        top10,
        success:ctx.flash.success,
        error:ctx.flash.error,
        page:Page(ctx.query,page,total)
    });
});

module.exports=router;